package com.jrx.anytxn.param.job.partnerShare;

import com.jrx.anytxn.common.uitl.BeanUtils;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.param.config.PartnerGeneralFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlPartnerGeneralLog;
import com.jrx.anytxn.param.mapper.ext.ExtTlPartnerGeneralLogMapper;
import com.jrx.anytxn.param.service.partner.IPartnerGeneralService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品放还款统计文件入库
 */
@Configuration
@EnableConfigurationProperties(PartnerGeneralFileConfig.class)
public class GeneralFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(GeneralFileConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private PartnerGeneralFileConfig partnerGeneralFileConfig;
    @Autowired
    private IPartnerGeneralService partnerGeneralService;
    @Resource
    private ExtTlPartnerGeneralLogMapper extTlPartnerGeneralLogMapper;

    @Bean
    public Job generalFileJob() {
        return jobBuilderFactory.get("generalFileJob")
                .start(generalFileStep())
                .build();
    }

    @Bean
    public Step generalFileStep() {
        return stepBuilderFactory.get("generalFileStep")
                .tasklet(generalFileTasklet())
                .build();
    }
    @Bean
    @StepScope
    public Tasklet generalFileTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.info("统计文件入库开始。。。。。。");
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String today = DateUtils.format(org.getToday(),"yyyyMMdd");

            String basePath = partnerGeneralFileConfig.getGeneralPath();

            String filePath = basePath + org.getTenantId() + File.separator + today + File.separator;

            File file = new File(filePath);
            File[] files = file.listFiles();

            List<TlPartnerGeneralLog> tlPartnerGeneralLogList = new ArrayList<>();
            for(int i=0;i<files.length;i++){
                String pathname = files[i].toString();
                try (FileReader reader = new FileReader(pathname);
                     BufferedReader br = new BufferedReader(reader)) {
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        TlPartnerGeneralLog log = partnerGeneralService.createTlPartnerGeneralLog(line);
                        tlPartnerGeneralLogList.add(log);
                    }
                } catch (Exception e) {
                    logger.error("读取统计文件异常，异常信息：",e);
                    throw new RuntimeException(e);
                }
            }

            List<TlPartnerGeneralLog> saveLogList = new ArrayList<>();
            Map<String,List<TlPartnerGeneralLog>> logMap =tlPartnerGeneralLogList.stream().collect(Collectors.groupingBy(TlPartnerGeneralLog::getProductId));
            logMap.forEach(
                (productId,list) ->{
                    TlPartnerGeneralLog logPerProduct = list.stream().reduce(list.get(0), (a, b) -> {
                        logger.info("a:{}", BeanUtils.toMap(a));
                        logger.info("b:{}", BeanUtils.toMap(b));
                        if(b.getId().equals(a.getId())){
                            return a;
                        }
                        a.setLoanTotalCount(a.getLoanTotalCount()+b.getLoanTotalCount());
                        a.setLoanTotalAmount(a.getLoanTotalAmount().add(b.getLoanTotalAmount()));
                        a.setCurrBalance(a.getCurrBalance().add(b.getCurrBalance()));
                        a.setPaymentCount(a.getPaymentCount()+b.getPaymentCount());
                        a.setPaymentAmount(a.getPaymentAmount().add(b.getPaymentAmount()));
                        a.setPaymentPrincipal(a.getPaymentPrincipal().add(b.getPaymentPrincipal()));
                        a.setPaymentInterest(a.getPaymentInterest().add(b.getPaymentInterest()));
                        a.setPaymentInstallmentFee(a.getPaymentInstallmentFee().add(b.getPaymentInstallmentFee()));
                        a.setPaymentPrepayFee(a.getPaymentPrepayFee().add(b.getPaymentPrepayFee()));
                        a.setPaymentPenalty(a.getPaymentPenalty().add(b.getPaymentPenalty()));
                        a.setPaymentCompound(a.getPaymentCompound().add(b.getPaymentCompound()));
                        a.setPaymentPreoffFee(a.getPaymentPreoffFee().add(b.getPaymentPreoffFee()));
                        a.setShareAmount(a.getShareAmount().add(b.getShareAmount()));
                        a.setShareInterest(a.getShareInterest().add(b.getShareInterest()));
                        a.setShareInstallmentFee(a.getShareInstallmentFee().add(b.getShareInstallmentFee()));
                        a.setSharePrepayFee(a.getSharePrepayFee().add(b.getSharePrepayFee()));
                        a.setSharePenalty(a.getSharePenalty().add(b.getSharePenalty()));
                        a.setShareCompound(a.getShareCompound().add(b.getShareCompound()));
                        a.setSharePreoffFee(a.getSharePreoffFee().add(b.getSharePreoffFee()));
                        return a;
                    });
                    saveLogList.add(logPerProduct);
                }
            );

            if(CollectionUtils.isNotEmpty(saveLogList)) {
                extTlPartnerGeneralLogMapper.insertbatch(saveLogList);
            }

            logger.info("统计文件入库结束。。。。。。");
            return RepeatStatus.FINISHED;
        };
    }
}
